<template>
  <div class="side-bar" :class="{ 'left-side-bar': isLeft }">
    <div
      :class="{ 'left-icon': isLeft, open: visible, close: !visible }"
      class="icon"
      @click="changeVisible"
    ></div>
    <div v-show="visible" class="side-bar__content">
      <p class="title">题号导航</p>
      <question-item
        class="main"
        :questionList="questionList"
        :allList="questionList"
        :sort="currentSort"
        @current-question="changeCurrentQuestion"
        ref="questionItemRef"
      />
      <div class="sort">
        <button
          class="btn btn-group"
          :class="{ active: currentSort === 1 }"
          @click="changeSort(1)"
        >
          题号排序
        </button>
        <button
          class="btn btn-group"
          :class="{ active: currentSort === 2 }"
          @click="changeSort(2)"
        >
          得分排序
        </button>
      </div>
    </div>
    <question-tools
      v-if="commentStore.currentQuestion.question_id"
      class="question-tools"
      :class="{ 'question-tools__left': isLeft && !visible }"
      @scale-question="scaleQuestion"
      @recover="scale = 1"
      :scale="scale"
      ref="questionToolsRef"
    />
    <page-tools
      class="page-tools"
      :class="{ 'page-tools__left': isLeft && !visible }"
      :currentQuestionNum="current"
      @change-current-question="changeCurrent"
      @change-similar-question="changeSimilar"
    />
    <!-- 相似题 -->
    <template v-if="commentStore.similar.isShow">
      <source-video
        class="source-video"
        :class="{ 'source-video__left': isLeft && !visible }"
        v-if="commentStore.similar.isShow && similarQuestionVideo"
        :url="similarQuestionVideo"
        :poster="getSimilarPoster"
      ></source-video>
    </template>
    <!-- 原题  -->
    <template v-else>
      <source-video
        v-if="
          commentStore.currentQuestion.original_video?.videoUrl ||
          commentStore.currentQuestion.original_video?.url
        "
        :url="
          commentStore.currentQuestion.original_video.videoUrl ||
          commentStore.currentQuestion.original_video?.url
        "
        :poster="commentStore.currentQuestion.original_video.imageUrl"
        class="source-video"
        :class="{ 'source-video__left': isLeft && !visible }"
      ></source-video>
    </template>
  </div>
</template>
<script setup>
import QuestionTools from './QuestionTools.vue'
import PageTools from './PageTools.vue'
import QuestionItem from './QuestionItem.vue'
import SourceVideo from './SourceVideo.vue'
import { categoryData } from '../constant'
import { useComment } from '@/stores/comment'
import $bus from '@/utils/tools/bus'
import {
  getQuestionList,
  getQuestionVideo,
  getRecommendVideo
} from '@/apis/comment/index'
import { ref, computed, onMounted, watchEffect, watch } from 'vue'
import { useAuthStore } from '@/stores/auth-store'
import { useRouter, useRoute } from 'vue-router'
import { getToken, uploadImg } from '../utils'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()
const userStore = useAuthStore()
const visible = ref(true)
const currentSort = ref(1)
const questionList = ref([])
const scale = ref(1)
const isLeft = ref(false)

const emits = defineEmits(['change-similar-question'])
const { setQuestionList, setVideoList } = useComment()
const commentStore = useComment()
const current = ref(1)
const questionItemRef = ref(null)
const videoList = ref([])

const changeSort = async type => {
  currentSort.value = type
  $bus.emit('sort-change', type)
  sessionStorage.setItem('question-sort', String(type))
  await getList()
  const index = questionList.value.findIndex(
    item => item.questionIndex === commentStore?.currentQuestion?.questionIndex
  )
  if (index > -1) current.value = index + 1
}

const scaleQuestion = desc => {
  if (desc === 'enlarge') {
    scale.value = parseFloat(scale.value.toFixed(1)) + 0.1
  } else {
    scale.value = parseFloat(scale.value.toFixed(1)) - 0.1
  }
}

const changeVisible = () => {
  visible.value = !visible.value
}
const changeCurrent = param => {
  if (param === 'prev') {
    current.value -= 1
  } else {
    current.value += 1
  }
  if (questionItemRef.value) {
    questionItemRef.value.changePage(current.value)
  }
}

const changeCurrentQuestion = val => {
  current.value = val + 1
  commentStore.setSimilar({
    isShow: false,
    list: []
  })
  $bus.emit('reset-similar')
}
const similarNum = ref(0)
const changeSimilar = val => {
  similarNum.value = val
  emits('change-similar-question', val)
}

const getList = async () => {
  const params = {
    task_id: route.query.task_id,
    class_id: route.query.class_id,
    order_by: currentSort.value
  }
  const { data, code } = await getQuestionList(params)
  if (code === 1) {
    const list = data || []
    setQuestionList(list)

    if (currentSort.value === 1) {
      questionList.value = list.map((item, index) => {
        return {
          questionIndex: index + 1,
          ...item
        }
      })
      commentStore.sortIndexList = JSON.parse(
        JSON.stringify(questionList.value)
      )
    } else {
      questionList.value = []
      list.forEach(element => {
        const questionIndex = commentStore.sortIndexList.find(
          item => item.question_id === element.question_id
        ).questionIndex
        questionList.value.push({ questionIndex: questionIndex, ...element })
      })
    }
    getVideo()
  } else {
    ElMessage.error('获取题目列表失败')
  }
}

const getVideo = async () => {
  const params = {
    user: {
      id: +userStore.userInfo.userId,
      name: userStore.userInfo.userName
    },
    question_ids: questionList.value.map(item => item.question_id)
  }
  const { data } = await getQuestionVideo(params)
  videoList.value = (data || []).map(item => {
    return {
      question_id: item.question_id,
      url: item.public_bind_video ? item?.public_bind_video.url : ''
    }
  })
  for (let index = 0; index < videoList.value.length; index++) {
    questionList.value[index].original_video = videoList.value[index]
  }
  setVideoList(videoList.value)
}

// 相似题视频
const similarQuestionVideo = ref('')
watchEffect(async () => {
  if (commentStore.similar.isShow) {
    const file = commentStore.similar.selectedList[similarNum.value].questionImg
    if (file) {
      await getToken()
      const result = await uploadImg(file)
      if (result.url) {
        const { data } = await getRecommendVideo({
          url: result.url,
          question_id: commentStore.similar.selectedList[similarNum.value].id,
          user: {
            id: +userStore.userInfo.userId,
            name: userStore.userInfo.userName
          }
        })
        similarQuestionVideo.value = (data || [])?.[0]?.url || ''
      }
    }
  }
})

const getSimilarPoster = computed(() => {
  return `${similarQuestionVideo.value}?vframe/jpg/offset/1`
})

watch(
  () => similarNum.value,
  () => {
    similarQuestionVideo.value = ''
  }
)

// TODO: 优化
onMounted(async () => {
  const flag = sessionStorage.getItem('is-left')
  isLeft.value = flag ? JSON.parse(flag) : false
  $bus.on('change-position', () => {
    isLeft.value = !isLeft.value
  })
  await getList()
  if (sessionStorage.getItem('question-sort'))
    currentSort.value = Number(sessionStorage.getItem('question-sort'))
  const forward = router.options.history.state?.forward || ''
  if (
    forward &&
    (forward.indexOf('studentResponse') > -1 ||
      forward.indexOf('studentCompare') > -1)
  ) {
    if (commentStore?.currentQuestion?.questionIndex) {
      current.value = questionList.value.findIndex(
        item =>
          item.questionIndex === commentStore?.currentQuestion?.questionIndex
      )
      changeCurrent()
    } else {
      current.value = 0
      changeCurrent()
    }
  } else {
    current.value = 0
    changeCurrent()
  }
})

defineExpose({
  scale
})
</script>
<style lang="less" scoped>
.side-bar {
  height: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  position: relative;

  .question-tools {
    position: absolute;
    left: -42px;
    bottom: 160px;
  }
  .page-tools {
    position: absolute;
    left: -249px;
    bottom: 68px;
  }

  .source-video {
    position: absolute;
    bottom: 300px;
    left: -44px;
  }

  &.left-side-bar {
    flex-direction: row-reverse;

    .question-tools {
      left: 324px;
      bottom: 160px;

      &__left {
        left: 24px;
      }
    }
    .page-tools {
      left: 324px;
      bottom: 68px;

      &__left {
        left: 24px;
      }
    }

    .source-video {
      left: 324px;
      bottom: 300px;

      &__left {
        left: 24px;
      }
    }
  }

  .icon {
    z-index: 100;
    height: 170px;
    width: 23px;
    cursor: pointer;
  }

  .close {
    background: url('@/assets/images/comment/sidebar-close.png') no-repeat
      center/cover;

    &.left-icon {
      background: url('@/assets/images/comment/left-sidebar-close.png')
        no-repeat center/cover;
    }
  }

  .open {
    background: url('@/assets/images/comment/sidebar-open.png') no-repeat
      center/cover;
    &.left-icon {
      background: url('@/assets/images/comment/left-sidebar-open.png') no-repeat
        center/cover;
    }
  }
  &__content {
    z-index: 100;
    height: 100%;
    width: 300px;
    padding: 24px 0;
    background: rgba(4, 188, 172, 0.088);
    border-radius: 24px 0 0 24px;
    color: #fff;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .title {
      padding: 15px;
      padding-bottom: 0;
      display: flex;
      justify-content: space-between;
      color: inherit;
      font-weight: 700;
      font-size: 24px;
    }
    .main {
      padding: 15px;
      flex: 1;
    }
    .sort {
      width: 100%;
      margin-bottom: 48px;
      padding: 4px 23px;
      display: flex;
      justify-content: center;

      .btn-group {
        flex: 1;
        &:first-child {
          border-radius: 8px 0 0 8px;
        }

        &:last-child {
          border-radius: 0 8px 8px 0;
        }
      }

      .btn {
        padding: 8px 0;
        border: solid 1px #fff;
        color: #fff;
        background: rgba(4, 188, 172, 0.088);
      }

      .active {
        background: #fff;
        color: #000;
      }
    }
  }
}
</style>
